package indi.h.security.encryption.asym;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.spec.InvalidParameterSpecException;

import javax.crypto.Cipher;

import org.bouncycastle.jce.spec.IESParameterSpec;

public class IESCryptImp extends AsymCryptImp implements IESCrypt {

	private IESParameterSpec eAlgorithmParameters;
	private IESParameterSpec dAlgorithmParameters;

	@Override
	public void beforeEncrypt() {
		if (eAlgorithmParameters == null) {
			super.beforeEncrypt();
			try {
				eAlgorithmParameters = cipher.getParameters().getParameterSpec(IESParameterSpec.class);
			} catch (InvalidParameterSpecException e) {
				e.printStackTrace();
			}
		} else {
			try {
				cipher.init(Cipher.ENCRYPT_MODE, outPublicKey, eAlgorithmParameters);
			} catch (InvalidKeyException e) {
				e.printStackTrace();
			} catch (InvalidAlgorithmParameterException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void customInit() {
		super.customInit();
		if (((IESCryptParameter) params).getIesCode() != null)
			setIES(((IESCryptParameter) params).getIesCode());
	}

	@Override
	public void beforeDecrypt() {
		try {
			if (outPrivateKey != null)
				cipher.init(Cipher.DECRYPT_MODE, outPrivateKey, dAlgorithmParameters);
			else
				cipher.init(Cipher.DECRYPT_MODE, privateKey, dAlgorithmParameters);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
	}

	@Override
	public IESCode getIES() {
		IESParameterSpec ps = eAlgorithmParameters;
		return new IESCode(ps.getDerivationV(), ps.getEncodingV(), ps.getMacKeySize(), ps.getCipherKeySize(),
				ps.getNonce(), ps.getPointCompression());
	}

	@Override
	public void setIES(IESCode iesCode) {
		dAlgorithmParameters = new IESParameterSpec(iesCode.getDerivation(), iesCode.getEncoding(),
				iesCode.getMacKeySize(), iesCode.getCipherKeySize(), iesCode.getNonce(),
				iesCode.isUsePointCompression());
	}

}
